package com.jswdwsx.esign.controller

import com.jswdwsx.esign.controller.request.FlowNotifyReq
import com.jswdwsx.esign.service.RequestService
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes

@Api(tags = ["通知回调接口（供e签宝调用）"])
@RestController
@RequestMapping("/v1/api/notify")
class NotifyController(
    private val requestService: RequestService
) {

    private val logger = LoggerFactory.getLogger(NotifyController::class.java)

    @PostMapping("/flow")
    @ApiOperation("通知回调接口（供e签宝调用）")
    fun flow(@RequestBody flowNotifyReq: FlowNotifyReq): String {

        val attributes = RequestContextHolder.getRequestAttributes() as ServletRequestAttributes
        val method = attributes.request.method
        logger.info("收到E签宝回调请求,http方法为${method},flowNotifyReq:$flowNotifyReq")

        when (flowNotifyReq.action) {

            "SIGN_FLOW_UPDATE" -> {
                logger.info("签署人[${flowNotifyReq.accountId}]已签署主体为[${flowNotifyReq.authorizedAccountId}]的流程[${flowNotifyReq.flowId}]")
            }

            "SIGN_FLOW_FINISH" -> {
                logger.info("流程[${flowNotifyReq.flowId}]已经以[${flowNotifyReq.statusDescription}（${flowNotifyReq.flowStatus}）]状态结束")
                requestService.completeRequest(flowNotifyReq)
            }

            else -> logger.info("已忽略E签宝次要回调，回调类型为：[${flowNotifyReq.action}]")
        }
        return "success"
    }
}
